class Solution {
    public int subarraysWithKDistinct(int[] nums, int k) {
        return findNumsofMost(nums, k) - findNumsofMost(nums, k - 1); 
    }
    private static final int maxn = 20001;
    private static int[] cnts = new int[maxn];
    private int findNumsofMost(int[] nums, int k) { 
        Arrays.fill(cnts, 1, nums.length + 1, 0);
        int ans = 0;
        for (int r = 0, l = 0, collect = 0; r < nums.length; r ++) { 
            if (++cnts[nums[r]] == 1) { 
                collect ++;
            }
            while (collect > k) { 
                if (--cnts[nums[l++]] == 0) { 
                    collect--;
                }
            }
            ans += r - l + 1;
        }
        return ans;
    }
}